package app.fugema.shop.main.center.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.base.common.app.LoginUtils;
import com.base.common.model.bean.PayResponse;
import com.base.common.model.bean.WeChatPayResponse;
import com.base.common.model.http.jackSon.JacksonUtils;
import com.base.common.netBeanPackage.LiveDataWrapper;
import com.base.common.utils.LogUtil;
import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.view.adapter.ada.BaseRVAdapter;
import com.base.common.view.adapter.ada.SingleRecyclerAdapter;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewObserver;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.List;

import androidx.lifecycle.Observer;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityChargeMoneyBinding;
import app.fugema.shop.databinding.WalletPayItemBinding;
import app.fugema.shop.helper.AlipayHelper;
import app.fugema.shop.helper.WeChatHelper;
import app.fugema.shop.main.center.vm.UserVM;
import app.fugema.shop.main.order.model.PaymentResult;
import app.fugema.shop.main.wallet.model.PayBen;
import app.fugema.shop.main.wallet.model.PayInfoResult;
import app.fugema.shop.main.wallet.model.WxpayInfo;

public class ChargeMoneyActivity extends BaseTitleActivity<ActivityChargeMoneyBinding, UserVM>
{

    private String userKey;

    private SingleRecyclerAdapter<PayBen, WalletPayItemBinding> adapter;

    private String payType;

    public static void start(Context context)
    {
        Intent intent = new Intent(context, ChargeMoneyActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charge_money);
    }

    @Override
    protected void initView()
    {
        super.initView();
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("充值",R.color.white);

        adapter = new SingleRecyclerAdapter<PayBen, WalletPayItemBinding>() {
            @Override
            public int getLayoutId()
            {
                return R.layout.wallet_pay_item;
            }

            @Override
            public void onBindViewHolder(WalletPayItemBinding binding, int position, PayBen bean)
            {
                super.onBindViewHolder(binding, position, bean);
            }

            @Override
            public void onItemClick(View view, BaseRVAdapter adapter, int onclickType, int position, PayBen bean)
            {
                if (bean.getPayType() == "0")
                {
                    LogUtil.e( "未获取到余额" );
                }
                setSelectPosition(position);
            }
        };
        adapter.setRadio(true);
        binding.rvRecyclerView.setAdapter(adapter);
        //充值
        binding.btnCharge.setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view)
            {
                  if( UIUtils.isNotEmpty(binding.etChargeMoney.getText().toString()) && Double.parseDouble(binding.etChargeMoney.getText().toString()) > 0 )
                  {
                     double money = Double.parseDouble(binding.etChargeMoney.getText().toString());

                     PayBen tPayben = adapter.getSelectBean();
                     payType = tPayben.getPayType();
                     LogUtil.e("ChargeMoneyActivity","payType = "+payType);
                     viewModel.chargeMoney(payType,money,userKey )
                              .observe(ChargeMoneyActivity.this, new BaseViewObserver<LiveDataWrapper<PayInfoResult>>()
                              {
                                  @Override
                                  protected void onSuccess(LiveDataWrapper<PayInfoResult> data)
                                  {
                                     if(data.data.isSuccess())
                                     {
                                         // 接口返回为 空
                                         if( UIUtils.isEmpty( data.data.getData() ) )
                                         {
                                             UIUtils.showToastSafesClose("支付信息为空");
                                         }
                                         else
                                         {
                                             // IndexOutOfBoundsException
                                             startCharge(data.data.getData().get(0));
                                         }

                                     }
                                  }
                              });
                  }
            }
        });

        binding.etChargeMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                stateChange(s.toString());
            }
        });

        // 默认 不给点击
        binding.btnCharge.setEnabled(false);
        binding.btnCharge.setAlpha(0.6f);

        //接收微信支付
        LiveEventBus.get(AppConstants.PAY_NOTIFY, PayResponse.class).observe(this, new Observer<PayResponse>() {
            @Override
            public void onChanged(PayResponse o)
            {
                if (o.getPayStatus() == PayResponse.PayStatus.STATUS_SUCCESS)
                {
                    //微信支付成功
                    UIUtils.showToastSafes("微信支付成功");
                    ChargeResultActivity.lunch(getActivity(), true);
                }
                else if( o.getPayStatus() == PayResponse.PayStatus.STATUS_CANCEL )
                {
                    //微信支付取消
                    UIUtils.showToastSafes("微信支付已取消");
                }
                else if(  o.getPayStatus() == PayResponse.PayStatus.STATUS_FAIL )
                { //微信支付失败
                    UIUtils.showToastSafes("微信支付失败");
                }
                else
                {
                    UIUtils.showToastSafes("未知错误");
                }
            }
        });

    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void initData()
    {
        super.initData();
        userKey = LoginUtils.getToken();

        viewModel.enablePaymentList(userKey).observe(this, new BaseViewObserver<LiveDataWrapper<PaymentResult>>(this) {
            @Override
            protected void onSuccess(LiveDataWrapper<PaymentResult> data)
            {
                List<PayBen> payBenList = PayBen.getPayListByPaymentType( data.data.getData() );
                //默认选择 第一个
                payBenList.get(0).setSelected(true);
                adapter.setDataList(payBenList);
            }
            @Override
            public boolean isEmptyData(LiveDataWrapper<PaymentResult> data)
            {
                return UIUtils.isEmpty(data.data.getData());
            }
        });

    }

    private void stateChange(String moneyStr)
    {
        //VerifyUtils.checkPhoneNumber(phone)
        if ( UIUtils.isNotEmpty(moneyStr) && Double.parseDouble(moneyStr) > 0)
        {
            binding.btnCharge.setEnabled(true);
            binding.btnCharge.setAlpha(1f);
        }
        else
        {
            binding.btnCharge.setEnabled(false);
            binding.btnCharge.setAlpha(0.6f);
        }
    }

    /**
     *  开始 调起 微信支付宝 支付
     * @param payDateInfo
     */
    private void startCharge(PayInfoResult.PayData payDateInfo)
    {
        String payIdStr = payDateInfo.getId();
        LogUtil.e("payId = " + payIdStr  );
        String type = payIdStr.substring(payIdStr.lastIndexOf(".") + 1 , payIdStr.length() );
        LogUtil.e("type = " + type  );
        switch (type)
        {
            case "walletPay"://钱包
//                        walletPay(stateBean);
//                        break;
            case "Alipay_App":
                //支付宝
                aliPay(payDateInfo.getUrl());
                break;
            case "WeiXinPay_App":
                //微信
                //"{\"prepayid\":\"wx09105107502939236da35e0f8c89170000\",\"timestamp\":1623207067,\"package\":\"Sign=WXPay\",\"sign\":\"133B7A895F5C73279B96FDC8319D2B6F\",\"partnerid\":\"1540498461\",\"noncestr\":\"34ED066DF378EFACC9B924EC161E7639\",\"appid\":\"wx312605eb4f303ee4\"}"
                wxpayReq(payDateInfo.getUrl());
                // 微信支付 结果 在 WXPayEntryActivity 中返回

                break;
            default:
                UIUtils.showToastSafes("支付方式未知");
                break;
        }
    }

    //支付宝
    public void aliPay(String aliPayStr)
    {
//"app_id=2019062065633602&biz_content=%7b%22out_trade_no%22%3a%22210531111638275197%22%2c%22product_code%22%3a%22QUICK_MSECURITY_PAY%22%2c%22subject%22%3a%22%e6%9c%a8%e6%9e%97%e6%a3%ae+%e7%94%b7%e5%a3%ab%e6%96%b0%e6%ac%be%e7%a7%8b%e5%ad%a3%e5%8d%ab%e8%a1%a3%e7%94%b7%e9%9f%a9%e7%89%88%e6%98%a5%e7%a7%8b%e5%ad%a6%e7%94%9f%e5%ae%bd%e6%9d%be%e6%bd%ae%e6%b5%81%e7%94%b7%e8%a3%85%e5%a4%96%e5%a5%97%e5%a4%a7%e7%a0%81%22%2c%22timeout_express%22%3a%2260m%22%2c%22total_amount%22%3a%22129.00%22%7d&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3a%2f%2fwww.fugema.cn%2fm-Android%2fPayment%2fNotify%2fHimall-Plugin-Payment-Alipay_App%2f&sign_type=RSA2&timestamp=2021-05-31+16%3a11%3a38&version=1.0&sign=Oeme1oWZK1kU6zmzQtCpkCitWH%2fiPzMATWEDggiPvOLWcR64zClxG073bDjR1vZ2PwhKksNLFuknpMZYEWGtDQZIZY7X80ML0bJntdC%2fBM0Iu7583soGTURMFvoIaH1F%2b%2fv3gAIspIhUHVOVqxk%2fh54rYbUczlwVzNN9OBmjx420ymagswQuXkL4cAqO6paIa%2b%2f5mdnVgxcRdw0g6OXCYoWI2EEtw4xLjYQGaYQm3RuvpNL8MStYZeprHEEg4WJN8EvYe%2bMIGhF7fEGDcAH2qXEe1wFnX0CHmVF%2fUAX5bDelaMgRxo8ajT9021AGN4Ovo8KmZskOyp3DwNGmYLsfhQ%3d%3d"
        AlipayHelper.pay(getActivity(), aliPayStr, new AlipayHelper.AlipayCallBack() {
            @Override
            public void onSucc()
            {
                UIUtils.showToastSafes("支付宝支付成功");
                //dismissAllowingStateLoss();
                ChargeResultActivity.lunch(getActivity(), true);
            }

            @Override
            public void onFail()
            {
                UIUtils.showToastSafes("支付宝支付失败",R.mipmap.ic_toast_warn);
                //dismissAllowingStateLoss();
            }
        });
    }


    //调起微信
    private void wxpayReq(String wxPayStr)
    {
        String jsonStr = wxPayStr;
        if( wxPayStr.contains("package") )
        {
            jsonStr =  wxPayStr.replace("package","packageX");
        }

        WxpayInfo data = JacksonUtils.getJsonBean(jsonStr ,WxpayInfo.class);

        WeChatPayResponse.PayInfoBean payInfoBean = new WeChatPayResponse.PayInfoBean();
        payInfoBean.setAppid(data.getAppid());
        payInfoBean.setNoncestr(data.getNoncestr());
        payInfoBean.setPackageX("Sign=WXPay");
        payInfoBean.setPartnerid(data.getPartnerid());
        payInfoBean.setPrepayid(data.getPrepayid());
        //String timeMillis = String.valueOf(System.currentTimeMillis() / 1000);
        //timeMillis
        payInfoBean.setTimestamp(data.getTimestamp());
        payInfoBean.setSign(data.getSign());
        WeChatHelper.pay(payInfoBean, false);
    }


}
